<template>
	<view :class="['lgtp', bgIndex === 1 ? 'lgtp1' : '']">
		<view class="content">
			<!-- 头部logo -->
			<view class="header">
				<view class="logo">校 点 通</view>
			</view>
			<!-- 主体表单 -->
			<view class="main">
				<view class="lgtx">登&nbsp;录</view>
				<wInput
					v-model="id"
					type="text"
					maxlength="13"
					placeholder="输入学号/工号"
					:focus="isFocus"
				></wInput>
				<wInput
					v-model="password"
					type="password"
					maxlength="11"
					placeholder="输入密码"
				></wInput>
			</view>
			<wButton 
				class="wbutton"
				text="登 录"
				:rotate="isRotate" 
				@click="startLogin"
			></wButton>
			
			
			<!-- 底部信息 -->
			<view class="footer">
				<navigator url="forget" open-type="navigate">找回密码</navigator>
			</view>
		</view>
		<background-switcher @change="v => bgIndex = v"/>
	</view>
</template>
<script>
	let	_this;
import wInput from '../../components/watch-login/watch-input.vue'
import wButton from '../../components/watch-login/watch-button.vue'
import BackgroundSwitcher from '@/components/background-switcher/background-switcher.vue'
// import { login } from '../../api/user.js'
export default {
  data() {
    return {
	  bgIndex: uni.getStorageSync('bgIndex') || 0,// 新增背景索引
      id: '',
      password: '',
      isRotate: false,
      isFocus: true,
	  mockData: {
	          '2023000000000': {  // 学生
	            type: 0,
	            name: '王同学',
	            id: '2023000000000',
	            roleName: '学生'
	          },
	          '2023111111111': {  // 教师
	            type: 2,  // 注意type对应跳转逻辑
	            name: '李老师',
	            id: '2023111111111',
	            roleName: '教师'
	          },
	          '9999999999999': {  // 管理员
	            type: 1,  // 注意type对应跳转逻辑
	            name: '系统管理员',
	            id: '9999999999999',
	            roleName: '管理员'
	          }
	        }
    };
  },
  components: { wInput, wButton,BackgroundSwitcher},
  mounted() {
    _this = this;
    this.isLogin();
  },
  onLoad(options) {
    if(options.bgIndex) {
      this.bgIndex = parseInt(options.bgIndex);
      uni.setStorageSync('bgIndex', this.bgIndex);
    }
  },
  
  // 确保页面显示时状态最新
  onShow() {
    this.bgIndex = uni.getStorageSync('bgIndex') || 0;
  },
  methods: {
   
    isLogin() {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          this.redirectToPage(userInfo.studentOrTeacher)
        }
      } catch (e) {
        console.error('读取存储失败', e)
      }
    },

    async startLogin() {
		// if (!/^\d{13}$/.test(this.id)) {
		//         return uni.showToast({ title: '账号应为13位数字', icon: 'none' })
		//       }
		      
		//       // 模拟登录逻辑
		//       if (this.mockData[this.id]) {
		//         const user = { 
		//           ...this.mockData[this.id],
		//           studentOrTeacher: this.mockData[this.id].type // 保持字段兼容
		//         }
		//         uni.setStorageSync('userInfo', user)
		//         this.redirectToPage(user.studentOrTeacher)
		//         return uni.showToast({ title: `模拟登录成功（${user.roleName}）`, icon: 'none' })
		//       }
		//       uni.$emit('updateUserType', { type: user.type });
		//       uni.showToast({ title: '模拟用户不存在', icon: 'none' });
      if (!/^\d{13}$/.test(this.id)) {
        return uni.showToast({ title: '账号应为13位数字', icon: 'none' })
      }
      if (this.password.length < 6) {
        return uni.showToast({ title: '密码至少6位字符', icon: 'none' })
      }

      this.isRotate = true
      uni.showLoading({ title: '登录中...' })

      try {
        const res = await login({id: this.id, password: this.password})
        if (res.code === 200) {
          uni.setStorageSync('userInfo', res.data)
          this.redirectToPage(res.data.studentOrTeacher)
        }
      } catch (error) {
        uni.showToast({ title: error.message || '登录失败', icon: 'none' })
      } finally {
        this.isRotate = false
        uni.hideLoading()
      }
    },
	
    redirectToPage(userType) {
      const pages = {
        0: '/pages/student/student',
        2: '/pages/teacher/teacher',
        1: '/pages/admin/admin'
      }
      
      const path = pages[userType] || '/pages/student/student'
      uni.reLaunch({
        url: path
      })
    }
  }
}
</script>
<style>
	@import url("../../components/watch-login/css/icon.css");
	@import url("./css/login.css");
</style>
